package com.trailwalker.inputmethod.activity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.trailwalker.JavaUtils.file.FileUtils;
import com.trailwalker.JavaUtils.string.StringUtils;
import com.trailwalker.inputmethod.InputMethodApplication;
import com.trailwalker.inputmethod.dialog.EditDialog;
import com.trailwalker.inputmethod.service.data.InputMethodDataService;
import com.trailwalker.inputmethod.service.entity.InputMethodKeys;
import com.trailwalker.javafx.core.entity.Intent;
import com.trailwalker.javafx.widget.dialog.JfxToast;
import com.trailwalker.javafx.core.activity.Activity;
import com.trailwalker.javafx.utils.image.ImageUtils;
import com.trailwalker.javafx.utils.resource.ResourceUtils;
import com.trailwalker.javafx.utils.stage.StageUtils;
import com.trailwalker.javafx.utils.storage.PreferencesManager;
import com.trailwalker.javafx.utils.style.AdaptUtils;
import com.trailwalker.javafx.utils.style.StyleUtils;
import com.trailwalker.javafx.utils.system.ApplicationUtils;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.util.Callback;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Trailwalker
 * @create 2021-09-05 16:08
 */
public class InputMethodMainActivity extends Activity {

    private static final String TAG = InputMethodMainActivity.class.getSimpleName();

    private ListView<InputMethodKeys> lvKeys;
    private ListView<String> lvPanels;

    private Activity mActivity;
    private AdaptUtils mAdaptUtils;
    private ImageView mIvClose;
    private ImageView mIvIconified;
    private ImageView mIvTheme;
    private TextField mTfSearch;
    private Button mBtnAddFile;
    private Button mBtnGenerateConfiguration;
    private Button mBtnPlayAll;
    private Map<String, ObservableList<InputMethodKeys>> inputMethodKeyMap;
    private ObservableList<String> mPanelList;
    private String mCurrentPanel;
    private String versionName = "_land_ios";

    @Override
    public void onCreate() {
        super.onCreate();
        initLoad();
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        if (mIvClose != null) {
            mIvClose.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (event.getButton().equals(MouseButton.PRIMARY)) {
                        ApplicationUtils.exit();
                    }
                }
            });
        }

        if (mIvIconified != null) {
            mIvIconified.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (event.getButton().equals(MouseButton.PRIMARY)) {
                        StageUtils.setIconified(getApplication().getStage());
                    }
                }
            });
        }

        if (mIvTheme != null) {
            mIvTheme.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (event.getButton().equals(MouseButton.PRIMARY)) {
                        ContextMenu contextMenu = new ContextMenu();
                        contextMenu.getStyleClass().add("context_menu_background");
                        CustomMenuItem lightMenuItem = new CustomMenuItem();

                        HBox hbItemLight = new HBox();
                        lightMenuItem.setContent(hbItemLight);
                        mAdaptUtils.setScaleWidth(hbItemLight, 100);
                        hbItemLight.setSpacing(mAdaptUtils.getScale(15));
                        hbItemLight.setAlignment(Pos.CENTER_LEFT);
                        hbItemLight.setOnMouseClicked(new EventHandler<MouseEvent>() {
                            @Override
                            public void handle(MouseEvent event) {
                                if (event.getButton().equals(MouseButton.PRIMARY)) {
                                    ObservableList<String> stylesheets = getApplication().getScene().getStylesheets();
                                    stylesheets.clear();
                                    stylesheets.add(ResourceUtils.getCss(InputMethodMainActivity.this, "lightTheme.css"));
                                    PreferencesManager.getInstance().putInt("theme", 0);
                                }
                            }
                        });

                        Label ivLight = new Label();
                        hbItemLight.getChildren().add(ivLight);
                        mAdaptUtils.setScaleSize(ivLight, 30);
                        StyleUtils.setBackgroundColor(ivLight, "#ffffff");

                        Label lblLight = new Label();
                        hbItemLight.getChildren().add(lblLight);
                        lblLight.getStyleClass().add("lbl_text_color");
                        mAdaptUtils.setScaleTextSize(lblLight, 25);
                        lblLight.setText("明亮");

                        CustomMenuItem darkMenuItem = new CustomMenuItem();

                        HBox hbItemDark = new HBox();
                        darkMenuItem.setContent(hbItemDark);
                        hbItemDark.setAlignment(Pos.CENTER_LEFT);
                        mAdaptUtils.setScaleWidth(hbItemDark, 100);
                        hbItemDark.setSpacing(mAdaptUtils.getScale(15));
                        hbItemDark.setOnMouseClicked(new EventHandler<MouseEvent>() {
                            @Override
                            public void handle(MouseEvent event) {
                                if (event.getButton().equals(MouseButton.PRIMARY)) {
                                    ObservableList<String> stylesheets = getApplication().getScene().getStylesheets();
                                    stylesheets.clear();
                                    stylesheets.add(ResourceUtils.getCss(InputMethodMainActivity.this, "darkTheme.css"));
                                    PreferencesManager.getInstance().putInt("theme", 1);
                                }
                            }
                        });

                        Label ivDark = new Label();
                        hbItemDark.getChildren().add(ivDark);
                        mAdaptUtils.setScaleSize(ivDark, 30);
                        StyleUtils.setBackgroundColor(ivDark, "#000000");

                        Label lblDark = new Label();
                        hbItemDark.getChildren().add(lblDark);
                        lblDark.getStyleClass().add("lbl_text_color");
                        mAdaptUtils.setScaleTextSize(lblDark, 25);
                        lblDark.setText("黑暗");

                        contextMenu.getItems().addAll(lightMenuItem, darkMenuItem);
                        contextMenu.show(mIvTheme, Side.BOTTOM, 0, 0);
                    }
                }
            });
        }

        if (mTfSearch != null) {
            mTfSearch.textProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {

                }
            });
        }

        if (mBtnAddFile != null) {
            mBtnAddFile.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    startActivity(new Intent(ImageActivity.class));
                }
            });
        }

        if (mBtnGenerateConfiguration != null) {
            mBtnGenerateConfiguration.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    if (StringUtils.isValid(mCurrentPanel)) {
                        ObservableList<InputMethodKeys> inputMethodKeyList = inputMethodKeyMap.get(mCurrentPanel);
                        StringBuilder sbConfig = new StringBuilder();
                        sbConfig.append("<MenuItem name=\"" + "panel_" + mCurrentPanel + versionName + "\" path=\"\">\n");

                        ArrayList<InputMethodKeys> key9List = new ArrayList<>();
                        ArrayList<InputMethodKeys> key26List = new ArrayList<>();
                        ArrayList<InputMethodKeys> keyNumList = new ArrayList<>();
                        ArrayList<InputMethodKeys> keyLetterList = new ArrayList<>();
                        ArrayList<InputMethodKeys> keyFunList = new ArrayList<>();
                        ArrayList<InputMethodKeys> keySymList = new ArrayList<>();
                        for (int i = 0; i < inputMethodKeyList.size(); i++) {
                            InputMethodKeys inputMethodKey = inputMethodKeyList.get(i);
                            String[] batchGroupSplit = inputMethodKey.getBatchGroup().split(" ");
                            if (batchGroupSplit.length > 0) {
                                for (int j = 0; j < batchGroupSplit.length; j++) {
                                    String batchGroup = batchGroupSplit[j];
                                    if (batchGroup.contains("key_9")) {
                                        key9List.add(inputMethodKey);
                                    }
                                    if (batchGroup.contains("key_26")) {
                                        key26List.add(inputMethodKey);
                                    }
                                    if (batchGroup.contains("key_num")) {
                                        keyNumList.add(inputMethodKey);
                                    }
                                    if (batchGroup.contains("key_letter")) {
                                        keyLetterList.add(inputMethodKey);
                                    }
                                    if (batchGroup.contains("key_fun")) {
                                        keyFunList.add(inputMethodKey);
                                    }
                                    if (batchGroup.contains("key_sym")) {
                                        keySymList.add(inputMethodKey);
                                    }
                                }
                            }
                        }
                        if (key9List.size() > 0) {
                            sbConfig.append("<KeyGroup name=\"key_9_group\">\n");
                            for (int i = 0; i < key9List.size(); i++) {
                                InputMethodKeys inputMethodKeys = key9List.get(i);
                                sbConfig.append("<Key id=\"" + inputMethodKeys.getName() + "\" desc=\"" + inputMethodKeys.getDesc() + "\" batchGroup=\"" + inputMethodKeys.getBatchGroup() + "\"/>\n");
                            }
                            sbConfig.append("</KeyGroup>\n");
                        }
                        if (key26List.size() > 0) {
                            sbConfig.append("<KeyGroup name=\"key_26_group\">\n");
                            for (int i = 0; i < key26List.size(); i++) {
                                InputMethodKeys inputMethodKeys = key26List.get(i);
                                sbConfig.append("<Key id=\"" + inputMethodKeys.getName() + "\" desc=\"" + inputMethodKeys.getDesc() + "\" batchGroup=\"" + inputMethodKeys.getBatchGroup() + "\"/>\n");
                            }
                            sbConfig.append("</KeyGroup>\n");
                        }
                        if (keyNumList.size() > 0) {
                            sbConfig.append("<KeyGroup name=\"key_num_group\">\n");
                            for (int i = 0; i < keyNumList.size(); i++) {
                                InputMethodKeys inputMethodKeys = keyNumList.get(i);
                                sbConfig.append("<Key id=\"" + inputMethodKeys.getName() + "\" desc=\"" + inputMethodKeys.getDesc() + "\" batchGroup=\"" + inputMethodKeys.getBatchGroup() + "\"/>\n");
                            }
                            sbConfig.append("</KeyGroup>\n");
                        }
                        if (keyLetterList.size() > 0) {
                            sbConfig.append("<KeyGroup name=\"key_letter_group\">\n");
                            for (int i = 0; i < keyLetterList.size(); i++) {
                                InputMethodKeys inputMethodKeys = keyLetterList.get(i);
                                sbConfig.append("<Key id=\"" + inputMethodKeys.getName() + "\" desc=\"" + inputMethodKeys.getDesc() + "\" batchGroup=\"" + inputMethodKeys.getBatchGroup() + "\"/>\n");
                            }
                            sbConfig.append("</KeyGroup>\n");
                        }
                        if (keyFunList.size() > 0) {
                            sbConfig.append("<KeyGroup name=\"key_fun_group\">\n");
                            for (int i = 0; i < keyFunList.size(); i++) {
                                InputMethodKeys inputMethodKeys = keyFunList.get(i);
                                sbConfig.append("<Key id=\"" + inputMethodKeys.getName() + "\" desc=\"" + inputMethodKeys.getDesc() + "\" batchGroup=\"" + inputMethodKeys.getBatchGroup() + "\"/>\n");
                            }
                            sbConfig.append("</KeyGroup>\n");
                        }
                        if (keySymList.size() > 0) {
                            sbConfig.append("<KeyGroup name=\"key_sym_group\">\n");
                            for (int i = 0; i < keySymList.size(); i++) {
                                InputMethodKeys inputMethodKeys = keySymList.get(i);
                                sbConfig.append("<Key id=\"" + inputMethodKeys.getName() + "\" desc=\"" + inputMethodKeys.getDesc() + "\" batchGroup=\"" + inputMethodKeys.getBatchGroup() + "\"/>\n");
                            }
                            sbConfig.append("</KeyGroup>\n");
                        }

                        sbConfig.append("</MenuItem>");

                        ClipboardContent content = new ClipboardContent();
                        String contentString = sbConfig.toString();
                        content.putString(contentString);
                        JfxToast.makeText(getApplication().getStage(), "面板" + mCurrentPanel + "配置已复制到剪贴板", JfxToast.LENGTH_SHORT).show();

                        Clipboard clipboard = Clipboard.getSystemClipboard();
                        clipboard.setContent(content);
                    }
                }
            });
        }
    }

    private void initData() {
        readJson();
    }

    private void readJson() {
        String path = InputMethodMainActivity.class.getClassLoader().getResource("json/appearanceConfig" + versionName + ".json").getPath();
        String s = FileUtils.readJsonFile(path);
        JSONObject jsonObject = JSON.parseObject(s);
        JSONObject panels = jsonObject.getJSONObject("panels");
        ArrayList<String> pannelList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : panels.entrySet()) {
            String panelName = entry.getKey();
            pannelList.add(panelName);
            JSONObject value = (JSONObject) entry.getValue();
            JSONObject keys = value.getJSONObject("keys");
            ObservableList<InputMethodKeys> inputMethodKeyList = FXCollections.observableArrayList();
            for (Map.Entry<String, Object> keysEntry : keys.entrySet()) {
                String keyName = keysEntry.getKey();
                if (keyName.contains("'")) {
                    keyName = getReplaceName(keyName);
                }
                InputMethodDataService inputMethodDataService = ((InputMethodApplication) getApplication()).getInputMethodDataService();
                InputMethodKeys inputMethodKeys = inputMethodDataService.getInputMethodKeysByName(keyName);
                if (inputMethodKeys == null) {
                    inputMethodKeys = new InputMethodKeys();
                    inputMethodKeys.setName(keyName);
                    inputMethodDataService.insertInputMethodKeys(inputMethodKeys);
                }
                inputMethodKeyList.add(inputMethodKeys);
            }
            SortedList<InputMethodKeys> sl = inputMethodKeyList.sorted(new Comparator<InputMethodKeys>() {

                @Override
                public int compare(InputMethodKeys o1, InputMethodKeys o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            inputMethodKeyMap.put(panelName, sl);
        }
        pannelList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        mPanelList.addAll(pannelList);
    }

    private String getReplaceName(String keyName) {
        String replaceName = keyName;
        if (keyName.contains("'")) {
            replaceName = keyName.replace("'", "singleQuotes");
        }
        return replaceName;
    }

    private void initLoad() {
        mActivity = this;
        mAdaptUtils = AdaptUtils.getInstance();
        mPanelList = FXCollections.observableArrayList();
        inputMethodKeyMap = new HashMap<>();
    }

    private void initView() {
        AnchorPane apRoot = new AnchorPane();
        setContentView(apRoot);

        BorderPane bpRoot = new BorderPane();
        apRoot.getChildren().add(bpRoot);
        mAdaptUtils.setMatchParentAnchorPane(bpRoot);
        bpRoot.getStyleClass().add("root_background");

        AnchorPane apTitle = new AnchorPane();
        bpRoot.setTop(apTitle);
        setTitleView(getApplication().getStage(), apTitle);
        mAdaptUtils.setScaleHeight(apTitle, 40);
        apTitle.getStyleClass().add("title_background");

        HBox hbTitle = new HBox();
        apTitle.getChildren().add(hbTitle);
        mAdaptUtils.setMatchParentAnchorPane(hbTitle);
        hbTitle.setAlignment(Pos.CENTER);
        mAdaptUtils.setScalePaddingLeftAndRight(hbTitle, 10);

        ImageView ivIcon = new ImageView();
        hbTitle.getChildren().add(ivIcon);
        ivIcon.setFitWidth(mAdaptUtils.getScale(25));
        ivIcon.setFitHeight(mAdaptUtils.getScale(25));
        ivIcon.setImage(new Image(ResourceUtils.getImage(this, "avatar.jpg")));

        Label lblTitle = new Label();
        hbTitle.getChildren().add(lblTitle);
        lblTitle.setText(versionName);
        mAdaptUtils.setScaleTextSize(lblTitle, 20);
        HBox.setMargin(lblTitle, new Insets(0, 0, 0, mAdaptUtils.getScale(15)));
        lblTitle.getStyleClass().add("lbl_title");

        HBox hbSearchContainer = new HBox();
        hbTitle.getChildren().add(hbSearchContainer);
        hbSearchContainer.getStyleClass().add("title_search_background");
        HBox.setMargin(hbSearchContainer, new Insets(0, 0, 0, mAdaptUtils.getScale(15)));
        mAdaptUtils.setBackgroundRadius(hbSearchContainer, 13);
        hbSearchContainer.setAlignment(Pos.CENTER);
        hbSearchContainer.setPrefHeight(mAdaptUtils.getScale(25));
        hbSearchContainer.setMaxHeight(mAdaptUtils.getScale(25));
        mAdaptUtils.setScaleWidth(hbSearchContainer, 150);

        mTfSearch = new TextField();
        hbSearchContainer.getChildren().add(mTfSearch);
        HBox.setHgrow(mTfSearch, Priority.ALWAYS);
        mTfSearch.setBackground(null);

        Region rEmpty = new Region();
        hbTitle.getChildren().add(rEmpty);
        HBox.setHgrow(rEmpty, Priority.ALWAYS);

        mIvTheme = ImageUtils.getImageView(this, 20, "theme_normal.png", "theme_press.png");
        hbTitle.getChildren().add(mIvTheme);
        HBox.setMargin(mIvTheme, new Insets(0, mAdaptUtils.getScale(30), 0, 0));

        mIvIconified = ImageUtils.getImageView(this, 20, "iconified_normal.png", "iconified_press.png");
        hbTitle.getChildren().add(mIvIconified);
        HBox.setMargin(mIvIconified, new Insets(0, mAdaptUtils.getScale(15), 0, 0));

        mIvClose = ImageUtils.getImageView(this, 20, "close_normal.png", "close_press.png");
        hbTitle.getChildren().add(mIvClose);

        AnchorPane apBottom = new AnchorPane();
        bpRoot.setBottom(apBottom);

        AnchorPane apCenter = new AnchorPane();
        bpRoot.setCenter(apCenter);

        BorderPane bpLvMediaContainer = new BorderPane();
        apCenter.getChildren().add(bpLvMediaContainer);
        mAdaptUtils.setMatchParentAnchorPane(bpLvMediaContainer);

        AnchorPane apLvMediaTop = new AnchorPane();
        bpLvMediaContainer.setTop(apLvMediaTop);
        apLvMediaTop.getStyleClass().add("add_file_container");
        mAdaptUtils.setScaleHeight(apLvMediaTop, 40);

        HBox hbAddFileContainer = new HBox();
        apLvMediaTop.getChildren().add(hbAddFileContainer);
        hbAddFileContainer.setAlignment(Pos.CENTER);
        mAdaptUtils.setMatchParentAnchorPane(hbAddFileContainer);

        mBtnPlayAll = new Button();
        hbAddFileContainer.getChildren().add(mBtnPlayAll);
        mBtnPlayAll.getStyleClass().add("btn_accent");
        mAdaptUtils.setScaleSize(mBtnPlayAll, 100, 25);
        mAdaptUtils.setScalePadding(mBtnPlayAll, 0);
        mAdaptUtils.setBackgroundRadius(mBtnPlayAll, 5);
        HBox.setMargin(mBtnPlayAll, mAdaptUtils.getMarginLeft(15, HBox.getMargin(mBtnPlayAll)));
        mBtnPlayAll.setText("播放全部");

        Region rAddFileEmpty = new Region();
        hbAddFileContainer.getChildren().add(rAddFileEmpty);
        HBox.setHgrow(rAddFileEmpty, Priority.ALWAYS);

        mBtnAddFile = new Button();
        hbAddFileContainer.getChildren().add(mBtnAddFile);
        mBtnAddFile.getStyleClass().add("btn_accent");
        mAdaptUtils.setScaleSize(mBtnAddFile, 70, 25);
        mAdaptUtils.setScalePadding(mBtnAddFile, 0);
        mAdaptUtils.setBackgroundRadius(mBtnAddFile, 5);
        HBox.setMargin(mBtnAddFile, mAdaptUtils.getMarginRight(15, HBox.getMargin(mBtnAddFile)));
        mBtnAddFile.setText("添加文件");

        mBtnGenerateConfiguration = new Button();
        hbAddFileContainer.getChildren().add(mBtnGenerateConfiguration);
        mBtnGenerateConfiguration.getStyleClass().add("btn_accent");
        mAdaptUtils.setScaleSize(mBtnGenerateConfiguration, 70, 25);
        mAdaptUtils.setScalePadding(mBtnGenerateConfiguration, 0);
        mAdaptUtils.setBackgroundRadius(mBtnGenerateConfiguration, 5);
        HBox.setMargin(mBtnGenerateConfiguration, mAdaptUtils.getMarginRight(15, HBox.getMargin(mBtnGenerateConfiguration)));
        mBtnGenerateConfiguration.setText("生成配置");

        AnchorPane apLvMediaLeft = new AnchorPane();
        bpLvMediaContainer.setLeft(apLvMediaLeft);

        lvPanels = new ListView<>(mPanelList);
        apLvMediaLeft.getChildren().add(lvPanels);
        mAdaptUtils.setMatchParentAnchorPane(lvPanels);
        lvPanels.getStyleClass().add("lv");
        lvPanels.setPadding(Insets.EMPTY);
        lvPanels.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
            @Override
            public ListCell<String> call(ListView<String> param) {
                ListCell<String> listCell = new ListCell<String>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);

                        HBox hbItemContainer = new HBox();
                        mAdaptUtils.setScaleHeight(hbItemContainer, 30);
                        hbItemContainer.setAlignment(Pos.CENTER);

                        if (!empty) {
                            HBox hbPanelNameContainer = new HBox();
                            hbItemContainer.getChildren().add(hbPanelNameContainer);
                            hbPanelNameContainer.setAlignment(Pos.CENTER);

                            Label lblPanleName = new Label();
                            hbPanelNameContainer.getChildren().addAll(lblPanleName);
                            lblPanleName.setText(item);
                            lblPanleName.getStyleClass().add("lbl_text_color");
                            lblPanleName.setAlignment(Pos.CENTER);
                            mAdaptUtils.setScaleTextSize(lblPanleName, 15);
                        }
                        this.setGraphic(hbItemContainer);
                    }
                };
                listCell.setPadding(Insets.EMPTY);
                listCell.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        mCurrentPanel = listCell.getItem();
                        lvKeys.setItems(inputMethodKeyMap.get(listCell.getItem()));
                    }
                });
                return listCell;
            }
        });

        AnchorPane apLvMediaCenter = new AnchorPane();
        bpLvMediaContainer.setCenter(apLvMediaCenter);

        lvKeys = new ListView<>();
        apLvMediaCenter.getChildren().add(lvKeys);
        mAdaptUtils.setMatchParentAnchorPane(lvKeys);
        lvKeys.getStyleClass().add("lv");
        lvKeys.setPadding(Insets.EMPTY);
        lvKeys.setCellFactory(new Callback<ListView<InputMethodKeys>, ListCell<InputMethodKeys>>() {
            @Override
            public ListCell<InputMethodKeys> call(ListView<InputMethodKeys> param) {

                ListCell<InputMethodKeys> listCell = new ListCell<InputMethodKeys>() {
                    @Override
                    protected void updateItem(InputMethodKeys item, boolean empty) {
                        super.updateItem(item, empty);

                        HBox hbItemContainer = new HBox();
                        mAdaptUtils.setScaleHeight(hbItemContainer, 30);
                        hbItemContainer.setAlignment(Pos.CENTER);
                        hbItemContainer.setSpacing(mAdaptUtils.getScale(30));

                        if (!empty) {
                            InputMethodKeys inputMethodKey = ((InputMethodApplication) getApplication()).getInputMethodDataService().getInputMethodKeysByName(item.getName());
                            item.setNiceName(inputMethodKey.getNiceName());
                            item.setDesc(inputMethodKey.getDesc());
                            item.setBatchGroup(inputMethodKey.getBatchGroup());
                            HBox hbIndexContainer = new HBox();
                            hbItemContainer.getChildren().add(hbIndexContainer);
                            //mAdaptUtils.setScaleWidth(hbIndexContainer, 40);
                            hbIndexContainer.setAlignment(Pos.CENTER_LEFT);
                            mAdaptUtils.setScaleWidth(hbIndexContainer, 170);

                            Label lblName = new Label();
                            hbIndexContainer.getChildren().addAll(lblName);
                            lblName.setText(item.getName());
                            lblName.getStyleClass().add("lbl_text_color");
                            lblName.setAlignment(Pos.CENTER);
                            mAdaptUtils.setScaleTextSize(lblName, 15);

                            HBox hbLblNickNameContainer = new HBox();
                            hbItemContainer.getChildren().add(hbLblNickNameContainer);
                            hbLblNickNameContainer.setAlignment(Pos.CENTER_LEFT);
                            mAdaptUtils.setScaleWidth(hbLblNickNameContainer, 210);

                            Label lblNickName = new Label();
                            hbLblNickNameContainer.getChildren().add(lblNickName);
                            lblNickName.setText(item.getNiceName());
                            lblNickName.getStyleClass().add("lbl_text_color");
                            mAdaptUtils.setScaleTextSize(lblNickName, 15);

                            HBox hbLblDescContainer = new HBox();
                            hbItemContainer.getChildren().add(hbLblDescContainer);
                            hbLblDescContainer.setAlignment(Pos.CENTER_LEFT);
                            HBox.setHgrow(hbLblDescContainer, Priority.ALWAYS);
                            Label lblDesc = new Label();
                            hbLblDescContainer.getChildren().add(lblDesc);
                            lblDesc.setText(item.getDesc());
                            lblDesc.getStyleClass().add("lbl_text_color");
                            mAdaptUtils.setScaleTextSize(lblDesc, 15);

                            HBox hbLblBatchGroupContainer = new HBox();
                            hbItemContainer.getChildren().add(hbLblBatchGroupContainer);
                            hbLblBatchGroupContainer.setAlignment(Pos.CENTER_LEFT);
                            mAdaptUtils.setScaleWidth(hbLblBatchGroupContainer, 300);
                            Label lblBatchGroup = new Label();
                            hbLblBatchGroupContainer.getChildren().add(lblBatchGroup);
                            lblBatchGroup.setText(item.getBatchGroup());
                            lblBatchGroup.getStyleClass().add("lbl_text_color");
                            mAdaptUtils.setScaleTextSize(lblBatchGroup, 15);
                        }
                        this.setGraphic(hbItemContainer);
                    }
                };
                listCell.setPadding(Insets.EMPTY);

                ContextMenu contextMenu = new ContextMenu();
                contextMenu.getStyleClass().add("context_menu_background");
                CustomMenuItem deleteMenuItem = new CustomMenuItem();

                HBox hbDelete = new HBox();
                deleteMenuItem.setContent(hbDelete);
                mAdaptUtils.setScaleWidth(hbDelete, 100);
                hbDelete.setAlignment(Pos.CENTER);
                hbDelete.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton().equals(MouseButton.PRIMARY)) {
//                            InputMethodKeys inputMethodKeys = listCell.getItem();
//                            ClipboardContent content = new ClipboardContent();
//
//                            String replace = inputMethodKeys.getNiceName().replace("符号", "符号键-");
//                            if (inputMethodKeys.getName().endsWith("S52")) {
//                                replace += "-其他";
//                            }
//                            content.putString(replace);
//
//                            Clipboard clipboard = Clipboard.getSystemClipboard();
//                            clipboard.setContent(content);

                            EditDialog editDialog = new EditDialog(getApplication().getStage());
                            editDialog.setInputMethodKeys(listCell.getItem());
                            editDialog.showDialog();
                            lvKeys.refresh();
                        }
                    }
                });

                Label lblDelete = new Label();
                hbDelete.getChildren().add(lblDelete);
                lblDelete.getStyleClass().add("lbl_text_color");
                mAdaptUtils.setScaleTextSize(lblDelete, 15);
                lblDelete.setText("编辑");
                contextMenu.getItems().add(deleteMenuItem);

                CustomMenuItem copyMenuItem = new CustomMenuItem();

                HBox hbCopy = new HBox();
                copyMenuItem.setContent(hbCopy);
                mAdaptUtils.setScaleWidth(hbCopy, 100);
                hbCopy.setAlignment(Pos.CENTER);
                hbCopy.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton().equals(MouseButton.PRIMARY)) {
                            ClipboardContent content = new ClipboardContent();
                            InputMethodKeys inputMethodKeys = listCell.getItem();
                            String contentString = "<Key id=\"" + inputMethodKeys.getName() + "\" desc=\"" + inputMethodKeys.getDesc() + "\" batchGroup=\"" + inputMethodKeys.getBatchGroup() + "\"/>";
                            content.putString(contentString);

                            Clipboard clipboard = Clipboard.getSystemClipboard();
                            clipboard.setContent(content);
                        }
                    }
                });

                Label lblCopy = new Label();
                hbCopy.getChildren().add(lblCopy);
                lblCopy.getStyleClass().add("lbl_text_color");
                mAdaptUtils.setScaleTextSize(lblCopy, 15);
                lblCopy.setText("复制");
                contextMenu.getItems().add(copyMenuItem);

                listCell.setContextMenu(contextMenu);

                return listCell;
            }
        });
    }
}
